package com.chengh.nami.web.controller.system;

import com.chengh.nami.core.annotation.SysLog;
import com.chengh.nami.common.domain.model.LoginUserEntity;
import com.chengh.nami.common.domain.pojo.SysRole;
import com.chengh.nami.common.domain.pojo.SysUser;
import com.chengh.nami.common.enums.system.BusinessType;
import com.chengh.nami.common.request.PageQuery;
import com.chengh.nami.common.response.PageData;
import com.chengh.nami.common.response.R;
import com.chengh.nami.common.utils.SecurityUtils;
import com.chengh.nami.system.domain.dto.UserDto;
import com.chengh.nami.system.domain.vo.UserVo;
import com.chengh.nami.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 用户控制器
 *
 * @author chengh
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/user")
@Tag(name = "SysUserController", description = "用户管理")
public class SysUserController {

    private final ISysUserService sysUserService;

    @GetMapping("/info")
    @Operation(summary = "获取登录用户信息")
    public R<UserVo> info() {
        LoginUserEntity loginUserEntity = SecurityUtils.getUserInfo();
        SysUser user = loginUserEntity.getUser();
        Set<String> permissions = loginUserEntity.getPermissions();
        List<SysRole> roles = loginUserEntity.getRoles();
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        userVo.setSysRoles(roles);
        userVo.setPermissions(permissions);
        return R.ok(userVo);
    }

    @GetMapping("/userInfos")
    @Operation(summary = "获取全部用户信息")
    public R<List<SysUser>> userInfos() {
        List<SysUser> infos = sysUserService.getInfos();
        return R.ok(infos);
    }

    @SysLog(title = "用户管理", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    @Operation(summary = "根据条件获取用户分页信息")
    public R<PageData<UserVo>> getUserList(UserDto userDto, PageQuery pageQuery) {
        PageData<UserVo> infos = sysUserService.getUserList(userDto, pageQuery);
        return R.ok(infos);
    }

    @PostMapping()
    @Operation(summary = "添加用户信息")
    public R<Void> addUser(@RequestBody SysUser user) {
        if (sysUserService.checkUserNameUnique(user.getUsername())) {
            return R.failed("新增失败，账号不允许重复");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return R.bool(sysUserService.insertUser(user));
    }
}
